package com.service.atf.reply.task;

import com.service.atf.base.exception.TFException;
import com.service.atf.base.model.Account;
import com.service.atf.base.model.TFLogout;
import com.service.atf.base.utils.ATFConstants;
import com.service.atf.base.utils.ATFLogger;
import com.service.atf.reply.ac.AccountManager;
import com.service.atf.reply.service.LogoutService6;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * User: luotao
 * Date: 12-3-27
 * Time: 15:10:00
 */
public class TaskAccount extends TimerTask {
    private ScheduledExecutorService scheduler;

    public TaskAccount() {
        scheduler.scheduleAtFixedRate(this, 1, 1, TimeUnit.DAYS);
        ATFLogger.sysinfo("����checkpoint�ƻ�����,�ӳ� : " + ATFConstants.TF_CHECKPOINT_LIMIT_MINUTE
                + " day ��� : " + ATFConstants.TF_CHECKPOINT_LIMIT_MINUTE + " day");
    }

    private LogoutService6 logoutService = new LogoutService6();

    @Override
    public void run() {

    }

    public void doTask() {
        byte[][] accounts = AccountManager.getInstance().getAllAccount();
        for (byte[] account : accounts) {
            if (account == null) continue;

            Account objAccount = new Account();
            objAccount.byte2Object(account);
            if ((char) objAccount.getConcurrLock() == '1') {
                ATFLogger.sysdebug("���û�����ʹ�ã������û� : " + objAccount.getCustomerCode());
                continue;
            }
            //����û�
            try {
                objAccount.setConcurrLock((byte) '1');
                AccountManager.getInstance().updateAccount(objAccount);
                int now = (int) new Date().getTime();
                if (now - objAccount.getLastActiveTime() <= 0) {
                    continue;
                }
                //�û��ǳ�
                TFLogout logout = new TFLogout();
                logout.setCustomerCode(objAccount.getCustomerCode());
                logout.setToken(objAccount.getToken());
                Map out = new HashMap();
                logoutService.execute(true, AccountManager.getInstance(), logout, out);
            } catch (Exception ex) {
                ex.printStackTrace();
                if (ex instanceof TFException) {
                    String msg = "�û��ǳ�ʱ�������,��ϸ��Ϣ : " + ex.toString() + " ���� : " + ((TFException) ex).getErrCode();
                    ATFLogger.syserr(msg);
                } else {
                    String msg = "�û��ǳ�ʱ�������,��ϸ��Ϣ : " + ex.toString();
                    ATFLogger.syserr(msg);
                }
            } finally {
                //������û�
                objAccount.setConcurrLock((byte) '0');
                AccountManager.getInstance().updateAccount(objAccount);
            }
        }
    }
}
